package org.example.scoresystem_backen.service.impl;

import org.example.scoresystem_backen.entity.Course;
import org.example.scoresystem_backen.mapper.CourseMapper;
import org.example.scoresystem_backen.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 课程服务实现类
 */
@Service
@Transactional
public class CourseServiceImpl implements CourseService {
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Override
    public Course createCourse(Course course) {
        // 检查课程名称是否已存在
        if (courseMapper.existsByName(course.getName())) {
            throw new RuntimeException("课程名称已存在");
        }

        // 检查课程代码是否已存在
        if (course.getCode() != null && courseMapper.existsByCode(course.getCode())) {
            throw new RuntimeException("课程代码已存在");
        }

        courseMapper.insert(course);
        return course;
    }
    
    @Override
    public Course updateCourse(Course course) {
        // 检查课程是否存在
        Course existingById = courseMapper.findById(course.getId());
        if (existingById == null) {
            throw new RuntimeException("课程不存在");
        }

        // 检查课程名称是否被其他课程使用
        Course existingCourseByName = courseMapper.findByName(course.getName());
        if (existingCourseByName != null && !existingCourseByName.getId().equals(course.getId())) {
            throw new RuntimeException("课程名称已被其他课程使用");
        }

        // 检查课程代码是否被其他课程使用
        if (course.getCode() != null) {
            Course existingCourseByCode = courseMapper.findByCode(course.getCode());
            if (existingCourseByCode != null && !existingCourseByCode.getId().equals(course.getId())) {
                throw new RuntimeException("课程代码已被其他课程使用");
            }
        }

        courseMapper.update(course);
        return course;
    }
    
    @Override
    public void deleteCourse(Integer id) {
        Course course = courseMapper.findById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        // 这里可以添加检查课程下是否还有成绩记录的逻辑
        courseMapper.deleteById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Course findById(Integer id) {
        Course course = courseMapper.findById(id);
        if (course != null) {
            return course;
        }
        throw new RuntimeException("课程不存在");
    }

    @Override
    @Transactional(readOnly = true)
    public Course findByName(String name) {
        Course course = courseMapper.findByName(name);
        if (course != null) {
            return course;
        }
        throw new RuntimeException("课程不存在");
    }

    @Override
    @Transactional(readOnly = true)
    public Course findByCode(String code) {
        Course course = courseMapper.findByCode(code);
        if (course != null) {
            return course;
        }
        throw new RuntimeException("课程不存在");
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Course> findAll() {
        return courseMapper.findAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Course> findAll(Pageable pageable) {
        // MyBatis不直接支持分页，这里简化处理
        List<Course> allCourses = courseMapper.findAll();
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), allCourses.size());
        List<Course> pageContent = allCourses.subList(start, end);
        return new PageImpl<>(pageContent, pageable, allCourses.size());
    }

    @Override
    @Transactional(readOnly = true)
    public boolean existsByName(String name) {
        return courseMapper.existsByName(name);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean existsByCode(String code) {
        return courseMapper.existsByCode(code);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Course> findByCredits(BigDecimal credits) {
        return courseMapper.findByCredits(credits);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Course> findByCreditsBetween(BigDecimal minCredits, BigDecimal maxCredits) {
        return courseMapper.findByCreditsBetween(minCredits, maxCredits);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Course> findByNameContaining(String name) {
        return courseMapper.findByNameContaining(name);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Course> findByCodeContaining(String code) {
        return courseMapper.findByCodeContaining(code);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Course> findAllOrderByName() {
        return courseMapper.findAllOrderByName();
    }

    // ========== 分页查询相关方法实现 ==========

    @Override
    @Transactional(readOnly = true)
    public org.example.scoresystem_backen.dto.PageResponse<Course> findCoursesWithPagination(org.example.scoresystem_backen.dto.PageRequest pageRequest) {
        // 验证分页参数
        pageRequest.validate();

        // 查询总记录数
        Long totalCount = courseMapper.countCoursesWithConditions(pageRequest);

        // 如果没有数据，返回空结果
        if (totalCount == 0) {
            return org.example.scoresystem_backen.dto.PageResponse.empty(pageRequest);
        }

        // 查询分页数据
        List<Course> courses = courseMapper.findCoursesWithPagination(pageRequest);

        // 构建分页响应
        return org.example.scoresystem_backen.dto.PageResponse.of(pageRequest, totalCount, courses);
    }

    // ========== 增强的删除操作实现 ==========

    @Override
    @Transactional
    public void deleteCourseWithCascade(Integer id) {
        // 检查课程是否存在
        Course course = courseMapper.findById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }

        // 先删除相关的成绩记录
        int deletedScores = courseMapper.deleteScoresByCourseId(id);

        // 再删除课程
        courseMapper.deleteById(id);

        // 记录日志
        System.out.println("删除课程: " + course.getName() + "，同时删除了 " + deletedScores + " 条相关成绩记录");
    }

    @Override
    @Transactional(readOnly = true)
    public List<org.example.scoresystem_backen.dto.CourseOptionDTO> getCourseOptions() {
        List<Course> courses = courseMapper.findAllOrderByName();
        return courses.stream()
                .map(course -> new org.example.scoresystem_backen.dto.CourseOptionDTO(
                        course.getId(),
                        course.getCode(),
                        course.getName(),
                        course.getCredits(),
                        course.getDescription()
                ))
                .collect(java.util.stream.Collectors.toList());
    }
}
